package com.ksy.common.dialog;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.view.View;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ksy.common.R;
import com.ksy.common.pick.OnWheelChangedListener;
import com.ksy.common.pick.WheelView;
import com.ksy.common.pick.adapters.ArrayWheelAdapter;
import com.ksy.common.utils.LogTool;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ksy.
 */

public class AreaChooseDialog extends CenterDialog implements OnWheelChangedListener {


    private ClickListener onClickListener;
    private List<Area> areasList = new ArrayList<>();
    private WheelView mViewProvince;
    private WheelView mViewCity;
    private WheelView mViewDistrict;
    private Handler handler = new Handler(Looper.getMainLooper());

    public AreaChooseDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_layout_dialog_picker_area);
        mViewProvince = (WheelView) findViewById(R.id.wheelFirst);
        mViewCity = (WheelView) findViewById(R.id.wheelSecond);
        mViewDistrict = (WheelView) findViewById(R.id.wheelThird);
        mViewProvince.addChangingListener(this);
        mViewCity.addChangingListener(this);
        mViewDistrict.addChangingListener(this);
        View dialog_cancel = findViewById(R.id.dialog_cancel);
        dialog_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        View dialog_enter = findViewById(R.id.dialog_enter);
        dialog_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Area areaP = null;
                Area areaC = null;
                Area areaA = null;
                int pCurrent = mViewProvince.getCurrentItem();
                int cCurrent = mViewCity.getCurrentItem();
                int aCurrent = mViewDistrict.getCurrentItem();
                if (pCurrent >= 0 && pCurrent < areasList.size()) {
                    areaP = areasList.get(pCurrent);
                    List<Area> citys = areaP.childs;
                    if (citys == null) {
                        citys = new ArrayList<>();
                    }
                    if (cCurrent >= 0 && cCurrent < citys.size()) {
                        areaC = citys.get(cCurrent);
                        List<Area> areas = areaC.childs;
                        if (areas == null) {
                            areas = new ArrayList<>();
                        }
                        if (aCurrent >= 0 && aCurrent < areas.size()) {
                            areaA = areas.get(aCurrent);
                        }
                    }
                }
                LogTool.e("areaP  " + areaP + "   areaC    " + areaC + "   areaA    " + areaA);
                if (onClickListener != null) {
                    onClickListener.enter(AreaChooseDialog.this, areaP, areaC, areaA);
                }
            }
        });
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    InputStream open = getContext().getAssets().open("area.json");
                    byte[] buffer = new byte[open.available()];
                    open.read(buffer);
                    open.close();
                    String jobJson = new String(buffer, "UTF-8");
                    Gson gson = new Gson();
                    List<Area> areas = gson.fromJson(jobJson, new TypeToken<List<Area>>() {
                    }.getType());
                    if (areas != null) {
                        areasList.addAll(areas);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        setUpData();
                    }
                });
            }
        };
        runnable.run();

    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        // TODO Auto-generated method stub
        if (wheel == mViewProvince) {
            updateCities();
        } else if (wheel == mViewCity) {
            updateAreas();
        } else if (wheel == mViewDistrict) {

        }
    }


    private void setUpData() {
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<>(getContext(), areasList));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(7);
        mViewCity.setVisibleItems(7);
        mViewDistrict.setVisibleItems(7);
        updateCities();
        updateAreas();
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        List<Area> citys = null;
        int pCurrent = mViewProvince.getCurrentItem();
        if (pCurrent >= 0 && pCurrent < areasList.size()) {
            Area areaP = areasList.get(pCurrent);
            citys = areaP.childs;
        }
        if (citys == null) {
            citys = new ArrayList<>();
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<>(getContext(), citys));
        if (citys.size() > 0) {
            mViewCity.setCurrentItem(0);
        }
        updateAreas();
    }

    @Override
    public void dismiss() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        super.dismiss();
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        List<Area> areas = null;
        int pCurrent = mViewProvince.getCurrentItem();
        if (pCurrent >= 0 && pCurrent < areasList.size()) {
            Area areaP = areasList.get(pCurrent);
            List<Area> citys = areaP.childs;
            if (citys == null) {
                citys = new ArrayList<>();
            }
            int cCurrent = mViewCity.getCurrentItem();
            if (cCurrent >= 0 && cCurrent < citys.size()) {
                Area area1 = citys.get(cCurrent);
                areas = area1.childs;
            }
        }
        if (areas == null) {
            areas = new ArrayList<>();
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<>(getContext(), areas));
        if (areas.size() > 0) {
            mViewDistrict.setCurrentItem(0);
        }
    }


    public void setOnClickListener(ClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public interface ClickListener {
        void enter(BaseDialog dialog, Area area, Area areaSub, Area areaSubSub);
    }

    @Keep
    public class Area {
        public String id;
        public String name;
        public double lat;
        public double lng;
        public List<Area> childs;

        @Override
        public String toString() {
            return name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Area area = (Area) o;

            if (!id.equals(area.id)) return false;
            return name.equals(area.name);
        }


        @Override
        public int hashCode() {
            int result = id.hashCode();
            result = 31 * result + name.hashCode();
            return result;
        }
    }
}
